package it.fuzzylogics.gwt.geolocation.client.core;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: hrothgar
 * Date: Jul 6, 2009
 * Time: 12:23:31 PM
 * To change this template use File | Settings | File Templates.
 */
public class Geolocator {
    private Position currPos;
    private boolean singleShot;
    private List<PositionHandler<Position>> positionHandlers = new ArrayList<PositionHandler<Position>>();
    private List<ErrorHandler<PositionError>> errorHandlers = new ArrayList<ErrorHandler<PositionError>>();

    public Geolocator(boolean singleShot) {
        this.singleShot=singleShot;
        initFuncts(this);
        if(singleShot)
            initSingleShotGeolocationEngine();
        else
            initGeolocationEngine();
    }
    
   public Geolocator() {
        this(false);
    }
    private native void initFuncts(Geolocator g)
        /*-{
       $wnd.PositionCallback = function (position) {
       g.@it.fuzzylogics.gwt.geolocation.client.core.Geolocator::handlePositionEvent(Lit/fuzzylogics/gwt/geolocation/client/core/Position;)(position);
       };

        $wnd.ErrorCallback = function (error) {
       g.@it.fuzzylogics.gwt.geolocation.client.core.Geolocator::handleError(Lit/fuzzylogics/gwt/geolocation/client/core/PositionError;)(position);
       };
        }-*/;
    
    private native void initSingleShotGeolocationEngine()   /*-{
        navigator.geolocation.getCurrentPosition($wnd.PositionCallback,$wnd.ErrorCallback);
        }-*/;

    private native void initGeolocationEngine()   /*-{
        var watchId = navigator.geolocation.watchPosition($wnd.PositionCallback,$wnd.ErrorCallback);
        }-*/;

    private native void stopGeolocationEngine()   /*-{
        navigator.geolocation.clearWatch($wnd.watchId);
        }-*/;

    static public final native boolean isAvailable()  /*-{ return navigator.geolocation ? true : false ; }-*/ ;

    public void handlePositionEvent(Position position){
        this.currPos = position;
        for(PositionHandler<Position> h : positionHandlers)
            h.handlePosition(currPos);
    }

     public void handleError(PositionError error){
        for(ErrorHandler<PositionError> h : errorHandlers)
            h.handleError(error);
    }

     public void stop(){
        if(!singleShot)
            stopGeolocationEngine();
    }
     public Position getCurrPos() {
        return currPos;
    }

     public boolean isSingleShot() {
        return singleShot;
    }

     public void addPositionHandler(PositionHandler h){
        positionHandlers.add(h);        
    }

     public void addErrorHandler(ErrorHandler h){
        errorHandlers.add(h);
    }
}
